package team.seekers.hula.auth.filter;

import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * @author GH
 */
public class RequestHeaderWrapper extends HttpServletRequestWrapper {
    private final MultiValueMap<String, String> headers = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap(8, Locale.ENGLISH));

    public RequestHeaderWrapper(HttpServletRequest request) {
        super(request);
        Collections.list(super.getHeaderNames()).forEach(name -> headers.addAll(name, Collections.list(super.getHeaders(name))));
    }

    public void addHeader(String name, String value){
        headers.add(name, value);
    }

    public List<String> removeHeader(String name){
        return headers.remove(name);
    }

    @Override
    public String getHeader(String name) {
        return Optional.ofNullable(headers.get(name))
                .filter(list -> !list.isEmpty())
                .map(list -> list.get(0))
                .orElse(null);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        return Collections.enumeration(headers.keySet());
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        return Collections.enumeration(headers.getOrDefault(name, Collections.emptyList()));
    }
}
